package com.tenchael.iblog.utils;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tenchael on 25/12/2017.
 */
public class MixAll {

	private static final String CHARSET = "UTF-8";

	/**
	 * 字节数组转字符串,采用UTF8编码
	 *
	 * @param bytes
	 * @return
	 */
	public static String utf8OfBytes(byte[] bytes) {
		try {
			return new String(bytes, CHARSET);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 字符串转字节数组,采用UTF8编码
	 *
	 * @param string
	 * @return
	 */
	public static byte[] getBytesWithUtf8(String string) {
		try {
			return string.getBytes(CHARSET);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 十六进制编码
	 *
	 * @param bytes
	 * @return
	 */
	public static String hexEncode(byte[] bytes) {
		return Hex.encodeHexString(bytes).toUpperCase();
	}

	/**
	 * 十六进制解码
	 *
	 * @param hex
	 * @return
	 */
	public static byte[] hexDecode(String hex) {
		try {
			return Hex.decodeHex(hex.toCharArray());
		} catch (DecoderException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 是否符合模式
	 *
	 * @param source
	 * @param pattern
	 * @return
	 */
	public static boolean isMatchedPattern(String source, Pattern pattern) {
		Matcher matcher = pattern.matcher(source);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}
}
